# -*- coding: UTF-8 -*-
import scrapy
import messAround.util.help as util


# 猫眼电影排行榜
class MaoyanTopSpider(scrapy.Spider):
    name = 'maoyan_top'

    allowed_domains = ['maoyan.com']

    start_urls = ['https://maoyan.com/']

    def start_requests(self):
        # 排行
        rank_urls = [
            {'name': 'TOP10', 'path': 'https://maoyan.com/board/4'},
            {'name': '热映口碑', 'path': 'https://maoyan.com/board/7'}
        ]

        for url in rank_urls:
            yield scrapy.Request(url=url['path'], meta={'name': url['name']}, callback=self.parse,
                                 headers=util.default_headers)

    # 排行榜
    def parse(self, response):
        category = response.meta['name']

        for index in range(1, 11):
            item_xpath = f'//*[@id="app"]/div/div/div/dl/dd[{index}]/'

            # title
            title = response.xpath(f'{item_xpath}div/div/div[1]/p[1]/a/text()').get()
            link = response.xpath(f'{item_xpath}div/div/div[1]/p[1]/a/@href').get()

            a = '//*[@id="app"]/div/div/div/dl/dd[1]/div/div/div[1]/p[1]/a'
            a = '//*[@id="app"]/div/div/div/dl/dd[2]/div/div/div[1]/p[1]/a'

            # time
            time = response.xpath(f'{item_xpath}div/div/div[1]/p[3]/text()').get()
            a = '//*[@id="app"]/div/div/div/dl/dd[1]/div/div/div[1]/p[3]'
            a = '//*[@id="app"]/div/div/div/dl/dd[2]/div/div/div[1]/p[3]'

            # 主演
            actor = response.xpath(f'{item_xpath}div/div/div[1]/p[2]/text()').get()
            a = '//*[@id="app"]/div/div/div/dl/dd[1]/div/div/div[1]/p[2]'
            a = '//*[@id="app"]/div/div/div/dl/dd[2]/div/div/div[1]/p[2]'

            # 封面
            cover = response.xpath(f'{item_xpath}a/img[2]/@data-src').get()
            a = '//*[@id="app"]/div/div/div/dl/dd[1]/a/img[2]'
            a = '//*[@id="app"]/div/div/div/dl/dd[2]/a/img[2]'

            # 评分
            score_integer = (response.xpath(f'{item_xpath}div/div/div[2]/p/i[1]/text()').get()).replace(".", '')
            score_fraction = response.xpath(f'{item_xpath}div/div/div[2]/p/i[2]/text()').get()
            score = f"{score_integer}.{score_fraction}"

            a = '//*[@id="app"]/div/div/div/dl/dd[1]/div/div/div[2]/p/i[1]'
            a = '//*[@id="app"]/div/div/div/dl/dd[1]/div/div/div[2]/p/i[2]'
            # 'https://maoyan.com/' +
            yield {
                'source': 0,
                'category': category,
                'no': index,
                'title': title,
                'link': f'https://maoyan.com{link}',
                'cover': cover,
                'actor': actor.replace("\n                ", '').replace("\n        ", ''),
                'time': time.replace("上映时间：", ''),
                'score_integer': score_integer,
                'score_fraction': score_fraction,
                'score': score,
            }
        pass
